<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddLine"
          v-if="optType == 'save' || optType == 'edit'"
          v-hasPermi="['pro:outsourcingorder:add']"
        >新增</el-button>
      </el-col>
    </el-row>
    <el-table border v-loading="loading" :data="lineList" @selection-change="handleSelectionChange">
      <el-table-column label="计划编号" align="center" prop="planNo" >
      </el-table-column>
      <el-table-column label="产品编号" align="center" prop="productCode" >
      </el-table-column>
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" width="50"/>

      <el-table-column label="单价" align="center" prop="price" >
        <template slot-scope="scope">
          <el-input-number
            :min="0"
            size="mini"
            style="width: 120px"
            v-model="scope.row.price"
            v-if="scope.row.updateStatus"
            @blur="getTotalPrice(scope.row)"
            @change="getTotalPrice(scope.row)"
          >
          </el-input-number>
          <span   v-else>{{scope.row.price}}</span>
        </template>
      </el-table-column>
      <el-table-column label="需求数量" align="center" prop="productQuantity" width="80" >
        <template slot-scope="scope">
<!--          <el-input
            type="text"
            size="mini"
            v-model="scope.row.productQuantity"
            v-if="scope.row.updateStatus"
            @blur="getTotalPrice(scope.row)"
          >
          </el-input>-->
          <span  >{{scope.row.productQuantity}}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品总价" align="center" prop="totalPrice" width="80">
        <template slot-scope="scope">
          {{scope.row.totalPrice}}
        </template>
      </el-table-column>
      <el-table-column label="BOM" align="center" prop="bomCode" >
        <template v-slot="scope">
          <el-input
            type="text"
            size="mini"
            v-model="scope.row.bomCode"
            readonly
            placeholder="请选择BOM"
            v-if="scope.row.updateStatus"
          >
            <el-button slot="append"  v-if="scope.row.updateStatus" icon="el-icon-search" style="padding:2px" @click="handleSelectBom(scope.row)"></el-button>
          </el-input>
          <span   v-else>{{scope.row.bomCode}}</span>

        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="optType=='save'||optType=='edit'">
        <template slot-scope="scope">
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="!scope.row.updateStatus"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pro:outsourcingorder:edit']">修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-else
            @click="handleSave(scope.row)"
            v-hasPermi="['pro:outsourcingorder:edit']"
          >确定</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.updateStatus"
            @click="handleCancel(scope.row)"
          >取消</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pro:outsourcingorder:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <BomSelectSingle ref="bomlist" :planning="{'productId':bomProductId}" @onSelected="onBomSelected" ></BomSelectSingle>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改外协订单明细对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请选择产品">
                <el-button
                  slot="append"
                  @click="handleSelectProduct"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
              <ItemSelect ref="itemSelect" item-or-product="PRODUCT" @onSelected="onItemSelected"></ItemSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" readonly  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="需求数量" prop="productQuantity">
              <el-input v-model="form.productQuantity" type="number" placeholder="请输入需求数量" @blur="getTotalPrice" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(元)" prop="price">
              <el-input v-model="form.price" type="number" placeholder="请输入单价" @blur="getTotalPrice" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
        <el-form-item label="产品总价(元)" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入产品总价" />
        </el-form-item>
        </el-col>
        </el-row>
        <el-tabs type="border-card" >
          <el-tab-pane label="BOM结构">
            <el-table
              v-if="refreshTable"
              v-loading="treeLoading"
              :data="treeList"
              row-key="id"
              :default-expand-all="true"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            >
              <el-table-column
                label="产品/物料名称"
                width="200"
                align="left"
                prop="itemName"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="产品/物料编号"
                width="140"
                align="center"
                prop="itemCode"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="物料类型" width="120" align="center" prop="itemType" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemType" />
                </template>
              </el-table-column>
              <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true" />
              <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true" />
              <el-table-column label="bom编号" width="200" align="center" prop="bomCode" :show-overflow-tooltip="true" />
              <el-table-column label="bom版本" width="120" align="center" prop="bomName" :show-overflow-tooltip="true" />
              <el-table-column label="图纸编号" width="140" align="center" prop="drawCode" :show-overflow-tooltip="true"/>
              <el-table-column label="使用量" align="center" prop="used" />
              <el-table-column label="使用比例" align="center" prop="proportional" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="物料清单" name="bomItem">
            <PlanBom ref="bomList" :planning="form" :optType="optType"></PlanBom>
            &lt;!&ndash;          <div >
                        <el-table v-loading="false" :data="itemList" >
                          <el-table-column type="index" label="序号" width="55" align="center"/>
                          <el-table-column label="物料编码" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
                          <el-table-column label="物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
                          <el-table-column label="规格型号" align="center" prop="itemSpc" :show-overflow-tooltip="true"/>
                          <el-table-column label="单位" width="100px" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
                          <el-table-column label="需求数量" width="120px" align="center" prop="quantity" :show-overflow-tooltip="true"/>
                          <el-table-column label="用料比例" width="100px" align="center" prop="proportional"/>
                        </el-table>
                        <pagination
                          v-show="itemTotal>0"
                          :total="itemTotal"
                          :page.sync="itemQueryParams.pageNum"
                          :limit.sync="itemQueryParams.pageSize"
                          @pagination="getBomItemList"
                        />
                      </div>&ndash;&gt;
          </el-tab-pane>
          <el-tab-pane label="BOM图纸">
            <li :key="file.drawUrl" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
              <el-link :href="`${file.drawUrl}`" :underline="false" target="_blank">
                <span class="el-icon-document"> {{ getFileName(file.drawUrl) }} </span>
              </el-link>
            </li>
          </el-tab-pane>
          <el-tab-pane label="BOM工序图纸" name="processPicture">
            <el-tabs type="border-card">
              <el-tab-pane v-for="(process,index) in processOptions" :key="index" :label="process.processName">
                <PDFView
                  :processId="process.processId"
                  :bomId="form.bomId"></PDFView>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
import { listLine, getLine, delLine, addLine, updateLine } from "@/api/mes/pro/outsourcingorder";
import ProductSelect from "@/components/productSelect/single.vue";
import BomSelectSingle from "@/components/mdBomSelect/single.vue";
import Template from "@/views/print/printtemplate/list.vue";
import PlanBom from "@/views/mes/pro/planning/bom/bom.vue";
import PDFView from "@/views/mes/md/bomgl/pdfView.vue";
import {listTree} from "@/api/mes/md/bomItem";
import {getBomGl} from "@/api/mes/md/bomgl";
import {listBomProcess} from "@/api/mes/pro/routeprocess";
import {copyValues} from "@/utils/ruoyi";
export default {
  name: "orderLine",
  components: {PDFView, PlanBom, Template, BomSelectSingle,  ProductSelect},
  props: {
    order: {
      type: Object,
      default: () => {orderId:null    }
    },
    optType:{
      type: String,
      default: 'edit'
    },orderLine:{
      type: Array,
      default: []
    }
  },
  data() {
    return {
      // 重新渲染表格状态
      refreshTable: true,
      // BOM结构
      treeLoading: true,
      // BOM结构数据
      treeList: [],
      // 工艺物料回显开关
      refresh: false,
      fileList:[{drawUrl:''}],
      // 工序列表
      processOptions: [],
      bomRow:null,
      bomProductId:null,
      oldRow: {},

      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 外协订单明细表格数据
      lineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,        productName: null,      },
      // 表单参数
      form: {  totalPrice: 0,        productQuantity: 0,        price: 0,  },
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "外协订单ID不能为空", trigger: "blur" }
        ],        productId: [
          { required: true, message: "产品ID不能为空", trigger: "blur" }
        ],        productCode: [
          { required: true, message: "产品编号不能为空", trigger: "blur" }
        ],        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],        productQuantity: [
          { required: true, message: "需求数量不能为空", trigger: "blur" }
        ],      }
    };
  },
  created() {
    //this.getList();
  },
  watch:{
    orderLine: {
      handler(newVal, oldVal) {
        this.lineList=[];
        this.lineList = copyValues(this.lineList,newVal)
       // this.lineList = newVal;
      }
    }
  },
  methods: {
    // 根据bomID获取树形结构
    getTree() {
      if(this.form.bomId!=0) {
        let bomId = this.form.bomId;
        listTree(bomId).then(response => {
          this.treeList = this.handleTree(response.data, 'bomId', 'parentId');
          this.treeLoading = false;
        })
      }
    },
    handleSave(row){
      row.updateStatus=false;
      this.$emit("refreshOrderLine",this.lineList);
    },
    handleCancel(row){
      row.productQuantity=this.oldRow.productQuantity;
      row.price=this.oldRow.price;
      row.totalPrice=this.oldRow.totalPrice;
      row.bomId=this.oldRow.bomId;
      row.bomName=this.oldRow.bomName;
      row.bomCode=this.oldRow.bomCode;
      row.updateStatus=false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.oldRow.productQuantity=row.productQuantity;
      this.oldRow.price=row.price;
      this.oldRow.totalPrice=row.totalPrice;
      this.oldRow.bomId=row.bomId;
      this.oldRow.bomName=row.bomName;
      this.oldRow.bomCode=row.bomCode;
      row.updateStatus=true;
    },
    handleSelectBom(row){
      this.bomRow=row;
      this.bomProductId=row.productId;
      this.$refs.bomlist.showFlag=true;
    },
    onBomSelected(row){
      this.bomRow.bomId = row.bomId;
      this.bomRow.bomName = row.bomName;
      this.bomRow.bomCode = row.bomCode;
      this.bomRow.updateStatus=false;
      this.bomRow.updateStatus=true;
      this.$emit("refreshOrderLine",this.lineList);
    },
    getTotalPrice(row){
      if(row.price!=null&&row.price!=''&&row.productQuantity!=null&&row.productQuantity!=''){
        row.totalPrice =  row.productQuantity*row.price;
      }
      this.$emit("refreshOrderLine",this.lineList);
    },

    /** 查询外协订单明细列表 */
    getList() {
      this.loading = true;
      listLine(this.queryParams).then(response => {
        let list= response.rows.map((item, index )=> {
          item.updateStatus=false;
          return item;
        })
        this.lineList = list;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        orderId: null,        productId: null,        productCode: null,        productName: null,
        totalPrice: 0,        productQuantity: 0,        price: 0,            createBy: null,        createTime: null,   bomId:null,bomCode:null,bomName:null,
        updateBy: null,        updateTime: null,        tenantId: null,        specification: null,        unitOfMeasure: null      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加外协订单明细";
    },
    handleInfoView(row){
      this.reset();
      this.form.id=row.id;
      this.form.price=row.price;
      this.form.productQuantity=row.productQuantity;
      this.form.totalPrice=row.totalPrice;
      this.form.productId=row.productId;
      this.form.productCode=row.productCode;
      this.form.bomId=row.bomId;
      this.form.bomCode=row.bomCode;
      this.form.bomName=row.bomName;
      this.form.productName=row.productName;
      this.form.specification=row.specification;
      this.form.unitOfMeasure=row.unitOfMeasure;
      this.title = "外协产品明细";
      this.getTree();
   /*   this.getBom();
      this.getProcess();
      this.getBomItemList();*/
      this.open = true;
    },
    getBom() {
      if(this.form.bomId!=0) {
        getBomGl(this.form.bomId).then(response => {
          this.bom = response.data;
        });
      }
    },
    //获取当前产品对应的生产工序
    getProcess() {
      if(this.form.bomId!=0) {
        listBomProcess(this.form.bomId).then(response => {
          this.processOptions = response.data;
        });
      }
    },
    // 获取物料组成列表
    getBomItemList() {

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.$emit('callParentMethod',this.form.orderId);
            });
          } else {
            this.form.orderId = this.order.orderId;
            addLine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$emit('callParentMethod',this.form.orderId);
            });
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const vm = this;
      this.$modal.confirm('是否确认删除？').then(function() {
        row.price=null;
        row.totalPrice=null;
        row.bomId=null;
        row.bomName=null;
        row.bomCode=null;
        vm.$emit("rollbackPlanRow",row);
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pro/line/export', {
        ...this.queryParams
      }, `line_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
